<?php
class Helper_Json
{	

	private $host;
	private $port;
	private $sock;
	
	/**
	 * 
	 * Constructor for the connection with the java server. 
	 * Data is send in JSON format.
	 * Constructor gets the host and port from the constants file and creates a socket.
	 */
	public function __construct() {
		$this->host = Kohana::config('constants.HOST');
		$this->port = Kohana::config('constants.PORT');
		
		$this->sock = socket_create(AF_INET, SOCK_STREAM, 0) or die("Error: couldn't create socket");	
	}

	
	/**
	 * 
	 * This function creates a connection with the Java server.
	 * If it succeeds a request is send and the function will wait for a response.
	 * When a response is recieved it will decode and returns the response.
	 * 
	 * @param array $data
	 */
	public function send_request($data) {
		$data = json_encode($data);
		try {
			socket_connect($this->sock, $this->host, $this->port) or die("error: could not connect to host\n");
			socket_write($this->sock, $data."\n", strlen($data) + 1) or die("error: failed to write to socket\n");
			$reply = socket_read($this->sock, 10000000, PHP_NORMAL_READ) or die("error: failed to read from socket\n");
			socket_close($this->sock);
		} catch (ErrorException $e){
			$reply = json_encode(array());
			$GLOBALS['json_connected'] = False;
		}	
		$reply = json_decode(utf8_encode($reply), true);
		
		return $reply;
	}
}